package com.system.manager.common.resolver;

import com.system.manager.common.annotation.CurrSubject;
import com.system.manager.common.constant.SysConstants;
import com.system.manager.modules.authorized.entity.Subject;
import com.system.manager.modules.authorized.enums.AuthorizationErrorCode;
import com.system.manager.modules.authorized.exception.AuthorizationException;
import com.system.manager.utils.ThreadLocalMap;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @Classname CurrSubjectResolver
 * @Description TODO 用来解析@CurrSubject注解
 * @Date 2021/10/17 17:31
 * @Created by 杨小鹏：【241960695@qq.com】
 */
public class CurrSubjectResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(CurrSubject.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {

        Subject subject = (Subject)ThreadLocalMap.get(SysConstants.HTTP_ATTRIBUTE_SUBJECT);
        if(subject == null){
            throw new AuthorizationException(AuthorizationErrorCode.IDENTITY_INFORMATION);
        }

        return subject;
    }
}
